package net.stuffrepos.bricknetcenter.plugins.bricklink;

import java.util.List;
import net.stuffrepos.bricknetcenter.database.DataManager;
import net.stuffrepos.bricknetcenter.database.DataManager.InformationManager.InformationNode;
import net.stuffrepos.bricknetcenter.database.InformationTree;
import net.stuffrepos.bricknetcenter.database.schema.Information;
import net.stuffrepos.bricknetcenter.http.HttpParser;
import net.stuffrepos.bricknetcenter.http.HttpResponse;
import net.stuffrepos.bricknetcenter.http.util.HtmlParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class BrickLinkCatalogParser extends HtmlParser implements HttpParser {

    private final Log log = LogFactory.getLog(BrickLinkCatalogParser.class);
    private final String provideSubNodeName;

    public BrickLinkCatalogParser(String providerSubNodeName) {
        this.provideSubNodeName = providerSubNodeName;
    }

    private InformationNode getRootNode() throws Exception {
        return BrickLinkHttpProvider.getProviderNode().addChild(Information.Type.Group, provideSubNodeName);
    }

    @Override
    public void parseDocument(HttpResponse response, Document document) throws Exception {
        InformationTree tree = new InformationTree();
        for (Element item : (List<Element>) document.getRootElement().getChildren("ITEM", document.getRootElement().getNamespace())) {
            tree.addChild(parseItem(item));
        }
        DataManager.getInstance().getInformationManager()
                .addInformationTree(getRootNode(), tree);
    }

    private InformationTree parseItem(Element item) throws Exception {
        if (log.isTraceEnabled()) {
            log.trace(parseItemType(item) + " => " + parseItemId(item));
        }

        InformationTree tree = new InformationTree(
                parseItemType(item),
                parseItemId(item));

        for (Element subItem : (List<Element>) item.getChildren()) {
            Information.Type subItemInformationType =
                    BrickLinkHttpProvider.getInformationTypeByTagName(
                    subItem.getName());
            if (subItemInformationType != null) {
                tree.addChild(
                        subItemInformationType,
                        subItem.getTextTrim());
            }

        }

        return tree;
    }

    private Information.Type parseItemType(Element item) throws Exception {
        return BrickLinkItemType.getByCode(
                item.getChildTextTrim("ITEMTYPE", item.getNamespace())).
                getInformationType();
    }

    private String parseItemId(Element item) {
        return item.getChildTextNormalize("ITEMID", item.getNamespace());
    }
}
